home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_09 / allison / rational.h < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-10  |  1.4 KB  |  67 lines

  1. #include <iostream.h>
  2. class ostream;
  3. class istream;
  4.  
  5. class Rational
  6. {
  7. public:
  8.     Rational(int n = 0, int d = 1);
  9.  
  10.     // Operations for rationals
  11.     friend Rational operator+(const Rational&, const Rational&);
  12.     friend Rational operator-(const Rational&, const Rational&);
  13.     friend Rational operator*(const Rational&, const Rational&);
  14.     friend Rational operator/(const Rational&, const Rational&);
  15.     Rational operator-() const;
  16.  
  17.     // I/O operations
  18.     friend ostream& operator<<(ostream&, const Rational&);
  19.     friend istream& operator>>(istream&, Rational&);
  20.  
  21. private:
  22.     int num;
  23.     int den;
  24.     void reduce();
  25. };
  26.  
  27. inline Rational::Rational(int n, int d)
  28. {
  29.     num = n;
  30.     den = d;
  31.     reduce();
  32. }
  33.  
  34. inline Rational operator+(const Rational& a, const Rational& b)
  35. {
  36.     Rational r(a.num * b.den + b.num * a.den, a.den * b.den);
  37.     r.reduce();
  38.     return r;
  39. }
  40.  
  41. inline Rational operator-(const Rational& a, const Rational& b)
  42. {
  43.     Rational r(a.num * b.den - b.num * a.den, a.den * b.den);
  44.     r.reduce();
  45.     return r;
  46. }
  47.  
  48. inline Rational operator*(const Rational& a, const Rational& b)
  49. {
  50.     Rational r(a.num * b.num, a.den * b.den);
  51.     r.reduce();
  52.     return r;
  53. }
  54.  
  55. inline Rational operator/(const Rational& a, const Rational& b)
  56. {
  57.     Rational r(a.num * b.den, a.den * b.num);
  58.     r.reduce();
  59.     return r;
  60. }
  61.  
  62. inline Rational Rational::operator-() const
  63. {
  64.     return Rational(-num,den);
  65. }
  66.  
  67.